package org.clockworkmages.games.anno1186.gui;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JComponent;

public abstract class AnimatedImage {

	/**
	 * A 0-1 state of the image. It may be defining the location, size or
	 * opacity of the image; or a combination of any of those.
	 */
	private double state = 0d;

	private double targetState = 0d;

	private double timeToGetToTargetState = 0;

	private Image image;

	public AnimatedImage(Image image) {
		this.image = image;
	}

	public abstract void draw(Graphics g, JComponent panel);

	public void setTargetState(double targetState, double timeToGetToTargetState) {
		this.targetState = targetState;
		this.timeToGetToTargetState = timeToGetToTargetState;
	}

	public void update(long interval) {
		if (timeToGetToTargetState <= 0) {
			return;
		}

		if (interval >= timeToGetToTargetState) {
			state = targetState;
		} else {
			double change = (state - targetState)
					* (interval / timeToGetToTargetState);
			state = state - change;
		}

		// GameUiUtil.logError(interval + " " + state);

		timeToGetToTargetState = timeToGetToTargetState - interval;
		if (timeToGetToTargetState <= 0) {
			timeToGetToTargetState = 0;
			while (this.state > 1) {
				this.state = this.state - 1;
			}
			while (this.state < 0) {
				this.state = this.state + 1;
			}
		}
	}

	public double getState() {
		return state;
	}

	protected Image getImage() {
		return image;
	}

	public void setState(double state) {
		this.state = state;
	}

}
